<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Organization extends Model
{
    /**
     * 可批量赋值的属性
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'code',
        'description',
        'logo',
        'address',
        'phone',
        'email',
        'website',
        'is_active',
        'parent_id',
    ];
    
    /**
     * 类型转换
     *
     * @var array
     */
    protected $casts = [
        'is_active' => 'boolean',
    ];
    
    /**
     * 获取组织的用户
     */
    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'organization_user')
                    ->withPivot('is_admin')
                    ->withTimestamps();
    }
    
    /**
     * 获取组织的管理员
     */
    public function admins()
    {
        return $this->users()->wherePivot('is_admin', true);
    }
    
    /**
     * 获取组织的子组织
     */
    public function children(): HasMany
    {
        return $this->hasMany(Organization::class, 'parent_id');
    }
    
    /**
     * 获取组织的父组织
     */
    public function parent(): BelongsTo
    {
        return $this->belongsTo(Organization::class, 'parent_id');
    }
}
